/*
* Copyright (c) 2021,
* All rights reserved.
*
* 文件名称：db_oper.c
* 创建日期：2021/12/19
* 摘 要：基础服务-数据库操作接口实现
*
* 当前版本：1.0
* 作 者：赵满刚
* 完成日期：
*/

#include "../public/dbhelper.h"
#include "../public/write_log.h"
#include "../public/protocol.h"
#include "../public/cJSON.h"
#include "db_oper.h"


/*******************************************************************************
*  func desc:   init_mysql_conn
*  input param: void
*  out   param: g_mysql_conn
*  retun value: void
********************************************************************************/
static void init_mysql_conn(void** mysql_conn)
{
    if (NULL == mysql_conn)
    {
        return;
    }   
    if (NULL == *mysql_conn)
    {
        *mysql_conn = InitDbCon2(MYSQL_LOCAL, MYSQL_USER, MYSQL_PASSWD, 
            MYSQL_PORT, MYSQL_DATABASE);    
    }
    return ;
}

/**
 * \brief 查询用户文件列表
 * 
 * \param [in]	user_conn 用户信息
 * \param [out] packet rsp
 * \return -1 -失败 other-成功
 */
int get_user_file_from_mysql(USER_CONNECT_INFO* user_conn, char* packet)
{
    if (NULL == user_conn || NULL == packet)
    {
        return 0;
    }
    
    char sql_str[MYSQL_MAX_SQL_LEN] = {0};
    struct DbResult *dbResult = NULL;
    int ret = 0;
    cJSON* file_list = NULL;
    file_list = cJSON_CreateObject();
    cJSON_AddNumberToObject(file_list, STR_TYPE, PROTO_TYPE_FILE_RSP);
    cJSON_AddNumberToObject(file_list, STR_IS_LAST, 1);
    /*查询*/
    void *g_mysql_conn = NULL;
    init_mysql_conn(&g_mysql_conn);
    if(NULL == g_mysql_conn)
    {
        write_log(LOG_ERROR,"connect mysql error");
        return -1;
    }    
    snprintf(sql_str, sizeof(sql_str), SQL_SELECT_FILES_BY_ID, user_conn->user_id);
    write_log(LOG_DEBUG,"%s",sql_str);
    if (NULL != g_mysql_conn)
    {
        //查
        dbResult = CreateDbResult();
        ret = db_QuerySql(g_mysql_conn, dbResult, sql_str);//querys
        write_log(LOG_DEBUG,"g not null %d dbresult %p",ret,dbResult);
        if (1 != ret)
        {
            if (dbResult)
            {
                FreeDbResult(dbResult);
                dbResult = NULL;
            }
            write_log(LOG_ERROR,"not have pwd by id:%d", user_conn->user_id);
            CloseDbCon(g_mysql_conn);
            g_mysql_conn = NULL;
            return -1;
        }
        if (NULL != dbResult && dbResult->nrow > 0)
        {
            int row = 0;
            write_log(LOG_DEBUG, "rows = %d", dbResult->nrow);
            for (row = 0; row < dbResult->nrow; row++)
            {
                cJSON* list = NULL;
                char tempname[LISTENQ] = {0};
                snprintf(tempname,sizeof(tempname), "%d", row);
                list = cJSON_AddObjectToObject(file_list, tempname);
                //循环遍历select结果每一行
                if (NULL != dbResult->rows[row][0])
                {
                    //FILE_ID
                    cJSON_AddNumberToObject(list, STR_FILE_ID, atoi(dbResult->rows[row][0]));
                }
                if (NULL != dbResult->rows[row][1])
                {
                    //FILE_NAME
                    cJSON_AddStringToObject(list, STR_FILE_NAME, dbResult->rows[row][1]);
                }
                if (NULL != dbResult->rows[row][2])
                {
                    //FAIL_PATH
                    cJSON_AddStringToObject(list, STR_FILE_PATH, dbResult->rows[row][2]);  
                }
                if (NULL != dbResult->rows[row][3])
                {
                    //upload_time
                    cJSON_AddNumberToObject(list, STR_UPLOAD_TIME, atol(dbResult->rows[row][3]));
                }
                if (NULL != dbResult->rows[row][3])
                {
                    //auth
                    cJSON_AddNumberToObject(list, STR_FILE_AUTH, atol(dbResult->rows[row][4]));
                }
   
            }
            cJSON_AddNumberToObject(file_list, STR_NUM, dbResult->nrow);
            strncpy(packet, cJSON_Print(file_list), MAXLINE); //get string from json
            write_log(LOG_DEBUG, "packe:%s", packet);
            FreeDbResult(dbResult);
            dbResult = NULL; 
        }
        else
        {
            write_log(LOG_ERROR,"not have result by id:%d", user_conn->user_id);
            CloseDbCon(g_mysql_conn);
            g_mysql_conn = NULL;
            return -1;
        }
        if (dbResult)
        {
            FreeDbResult(dbResult);
            dbResult = NULL; 
        }
        CloseDbCon(g_mysql_conn);
        g_mysql_conn = NULL;
    }//mysqlconn

    return SUCCESS;
}

/**
 * \brief 用户信息校验
 * 
 * \param [in]	password 密码
 * \param [in]	user_conn 用户信息
 * \return -1 -失败 other-成功
 */
int verify_user_info_from_mysql(char* password, USER_CONNECT_INFO* user_conn)
{
    if (NULL == password || NULL == user_conn)
    {
        return FAIL;
    }

    char sql_str[MYSQL_MAX_SQL_LEN]={0};
    struct DbResult *dbResult = NULL;
    int ret = 0;
    char pwd[MAX_LEN_PASSWORD] = {0};

    /*查询pwd*/
    void *mysql_conn = NULL;
    init_mysql_conn(&mysql_conn);
    if(NULL == mysql_conn)
    {
        write_log(LOG_ERROR,"connect mysql error");
        return FAIL;
    }
    snprintf(sql_str, sizeof(sql_str), SQL_SELECT_USERINFO_BY_USERNAME, user_conn->user_name);
    write_log(LOG_DEBUG, "%s", sql_str);
    if (NULL != mysql_conn)
    {
        //查pwd
        dbResult = CreateDbResult();
        ret = db_QuerySql(mysql_conn, dbResult, sql_str);//querys
        write_log(LOG_DEBUG,"g not null %d dbresult %p",ret,dbResult);
        if (1 != ret)
        {
            if (dbResult)
            {
                FreeDbResult(dbResult);
                dbResult = NULL;
            }
            write_log(LOG_ERROR,"not have pwd by usernmae:%s", user_conn->user_name);
            CloseDbCon(mysql_conn);
            mysql_conn = NULL;
            return FAIL;
        }
        if (NULL != dbResult && dbResult->nrow > 0)
        {
            if (NULL != dbResult->rows[0][0])
            {
                write_log(LOG_DEBUG, "username:%s pwd from mysql is:%s", user_conn->user_name, dbResult->rows[0][0]);
                strncpy(pwd,dbResult->rows[0][0],MAX_LEN_PASSWORD);
            } 
            else
            {
                write_log(LOG_ERROR,"not have result by usernmae:%s", user_conn->user_name);
                CloseDbCon(mysql_conn);
                mysql_conn = NULL;
                return FAIL;
            }
            if (NULL != dbResult->rows[0][1])
            {
                user_conn->user_id = atoi(dbResult->rows[0][1]);
            }
            if (NULL != dbResult->rows[0][2])
            {
                strncpy(user_conn->icon, dbResult->rows[0][2], MAX_LEN_ICON);
            }
            FreeDbResult(dbResult);
            dbResult = NULL; 
        }
        else
        {
            write_log(LOG_ERROR,"not have result by username:%s", user_conn->user_name);
            CloseDbCon(mysql_conn);
            mysql_conn = NULL;
            return FAIL;
        }
        if (dbResult)
        {
            FreeDbResult(dbResult);
            dbResult = NULL; 
        }
    }//mysqlconn
    /*比较pwd*/
    write_log(LOG_DEBUG,"compare begin");
    CloseDbCon(mysql_conn);
    mysql_conn = NULL;
    if (0 != strncmp(pwd, password, MAX_LEN_PASSWORD))
    {
        return FAIL; 
    }
    return SUCCESS;
}